//
//  PosterViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/11/16.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "XLCardSwitch.h"
#import "TT_ShareManager.h"

#import "PosterViewController.h"

@interface PosterViewController ()<XLCardSwitchDelegate>

@property (nonatomic, strong) XLCardSwitch *cardSwitch;

@property (nonatomic, strong) NSMutableArray *models;

@property (nonatomic, copy) NSString *code;
@property (nonatomic, copy) NSString *codeUrl;

@property (nonatomic, copy) UIImage *codeImage;

@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, assign) NSInteger selIndex;

@end

@implementation PosterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    [self request_code];
    
}

- (void)initView {
    
    self.title = @"邀请好友"; 
    self.view.backgroundColor = UIColorHex(0xf8f8f8);
    self.selIndex = 0;
    
    //初始化
    self.cardSwitch = [[XLCardSwitch alloc] initWithFrame:CGRectZero];
    //设置代理方法
    self.cardSwitch.delegate = self;
    //分页切换
    self.cardSwitch.pagingEnabled = true;

    [self.view addSubview:self.cardSwitch];
    [self.view addSubview:self.saveBtn];
    [self.view addSubview:self.shareBtn];

}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.cardSwitch.frame = CGRectMake(0, 0, TTScreenWidth, TTScreenHeight - kStatusBarHeight - NavBar_Height - Bottom_SafeHeight - 80);
    
    self.saveBtn.frame = CGRectMake(15, TTScreenHeight - kStatusBarHeight - NavBar_Height - Bottom_SafeHeight - 80, (TTScreenWidth/2 - 20), 40);
    self.shareBtn.frame = CGRectMake((TTScreenWidth/2 +5), TTScreenHeight - kStatusBarHeight - NavBar_Height - Bottom_SafeHeight - 80, (TTScreenWidth/2 - 20), 40);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.saveBtn pp_clipCorners:UIRectCornerAllCorners radius:20 border:1 color:UIColorHex(0xff4242)];
        [self.shareBtn pp_clipCorners:UIRectCornerAllCorners radius:20];

    });
}

- (void)shareAction {
    
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@%@?myCode=%@&myUser=%@",BA_GlobalH5_Domain,@"/download",self.code,[Utilities stringToUnicode:[TTUserModel sharedObject].nickname]];
    model.title = @"婚前婚后用户端";
    model.content = @"婚前婚后邀您体验";
    model.image = [UIImage imageNamed:@"ba_logo"];
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (void)saveAction {
    
    UIImage *viewImage = [self cacheImage];
    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
    
    [SVProgressHUD showSuccessWithStatus:@"保存成功，请去相册查看"];
    [SVProgressHUD dismissWithDelay:1];
}

- (UIImage *)cacheImage {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.selIndex inSection:0];
    UICollectionViewCell * cell = (UICollectionViewCell *)[self.cardSwitch.collectionView cellForItemAtIndexPath:indexPath]; //即为要得到的cell
    UIGraphicsBeginImageContextWithOptions(cell.bounds.size, 0, [[UIScreen mainScreen] scale]);
    [cell.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

- (void)fillViewWithData {
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSString *string = self.codeUrl; //加入二维码url
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];

    CIImage *image = [filter outputImage];
    CGAffineTransform transform = CGAffineTransformMakeScale(10.0f, 10.0f);
    CIImage *output = [image imageByApplyingTransform: transform];
    UIImage *newImage = [UIImage imageWithCIImage:output scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
    self.codeImage = newImage;

    [self buildData];
}

- (void)buildData {

    self.models = [NSMutableArray new];

    NSArray *arr = @[B_POSTER_IMG1,
                     B_POSTER_IMG2,
                     B_POSTER_IMG3];
    arr = @[
        @"qrcode_1.webp",
        @"qrcode_2.webp",
        @"qrcode_3.webp"
    ];
    
    for (int i = 0; i<3; i++) {
        PosterCardModel *model = [[PosterCardModel alloc] init];

        //model.imageUrl = arr[i];
        model.local_imageUrl = arr[i];
        model.codeImage = self.codeImage;
        model.title = @"123";
        
        [self.models addObject:model];
    }
    
    //设置卡片数据源
    self.cardSwitch.models = self.models;
    
}

#pragma mark -
#pragma mark CardSwitchDelegate
- (void)cardSwitchDidClickAtIndex:(NSInteger)index {
    NSLog(@"点击了：%zd",index);
}

- (void)cardSwitchDidScrollToIndex:(NSInteger)index {
    self.selIndex = index;
}

#pragma mark -
#pragma mark 手动切换方法
- (void)switchPrevious {
    NSInteger index = self.cardSwitch.selectedIndex - 1;
    index = index < 0 ? 0 : index;
    [self.cardSwitch switchToIndex:index animated:true];
}

- (void)switchNext {
    NSInteger index = self.cardSwitch.selectedIndex + 1;
    index = index > self.models.count - 1 ? self.models.count - 1 : index;
    [self.cardSwitch switchToIndex:index animated:true];
}

- (UIButton *)saveBtn {
    if (!_saveBtn) {
        _saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_saveBtn setTitle:@"保存海报" forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_saveBtn setTitleColor:UIColorHex(0xff4242) forState:UIControlStateNormal];
        [_saveBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
        [_saveBtn setBackgroundColor:UIColorHex(0xffffff)];

    }
    return _saveBtn;
}

- (UIButton *)shareBtn {
    if (!_shareBtn) {
        _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _shareBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_shareBtn setTitle:@"分享赚钱" forState:UIControlStateNormal];
        [_shareBtn setTitleColor:UIColorHex(0xffffff) forState:UIControlStateNormal];
        [_shareBtn setBackgroundColor:UIColorHex(0xff4242)];
        [_shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareBtn;
}

- (void)request_code {
            
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyCode];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                weakSelf.code = [resultDic valueForKey:@"code"];
                weakSelf.codeUrl = [resultDic valueForKey:@"codeUrl"];
                
                [weakSelf fillViewWithData];
            } else {
                
                NSString * message = [data valueForKey:@"message"];
                [SVProgressHUD showErrorWithStatus:message];
                [SVProgressHUD dismissWithDelay:1];

            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}


@end
